// Copyright (C) 2005 Taylor L. Riche <riche@cs.utexas.edu>
//  
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software 
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// $Id: tshtools.cc 61 2005-07-28 17:01:05Z richetl $
//
// -----------------------------------------------------------------

#include "tshtools.hh"

using namespace tt;

TshReader::TshReader(std::string fn) throw(std::invalid_argument) : TraceReader(fn)
{
  tshFile = fopen(filename.c_str(), "r");
  if(tshFile == NULL) {
    throw std::invalid_argument("The input trace specified does not exist.");
  }
  return;
}

TshReader::~TshReader()
{
  if(tshFile != NULL) {
    fclose(tshFile);
  }
  return;
}

void
TshReader::readPacket(Packet & newPacket) throw(std::underflow_error)
{
  TshFormat tshPacket;
  int amountRead;
  uint32_t data;
  
  for(uint32_t i = 0; i < sizeof(tshPacket); i += sizeof(data)) {
    amountRead = fread(&data, sizeof(data), 1, tshFile);
    if(amountRead != 1) {
      if(i != 0) {
 	throw std::underflow_error("Truncated tsh trace file.");
      }
    }
    memcpy(((char*)&tshPacket) + i, &data, sizeof(data));
  }
  newPacket.tsSec = ntohl(tshPacket.tsSec);
  newPacket.tsUSec = ntohl(tshPacket.tsUSec << 8);
  memcpy(&newPacket.ipHdr, tshPacket.payload, sizeof(iphdr));
  memcpy(&newPacket.tcpHdr, tshPacket.payload + sizeof(iphdr), sizeof(tcphdr));
  return;
}

void
TshWriter::writePacket(const Packet & targetPacket)
{
  TshFormat tshPacket;
  
  tshPacket.tsSec = htonl(targetPacket.tsSec);
  tshPacket.tsUSec = htonl(targetPacket.tsUSec) >> 8;
  //cerr << ntohl(tshPacket.tsSec) << "\t" << ntohl(tshPacket.tsUSec << 8) << endl;
  tshPacket.interface = 0;
  memcpy(tshPacket.payload, &targetPacket.ipHdr, sizeof(iphdr) + sizeof(tcphdr));
  fwrite(&tshPacket, sizeof(tshPacket), 1, tshFile);
  return;
}

TshWriter::TshWriter(std::string fn) throw(std::invalid_argument) : TraceWriter(fn)
{
  tshFile = fopen(filename.c_str(), "w");
  if(tshFile == NULL) {
    throw std::invalid_argument("There was an error opening the output file.");
  }
  return;
}

TshWriter::~TshWriter()
{
  if(tshFile != NULL) {
    fclose(tshFile);
  }
  return;
}
